﻿CREATE PROCEDURE [maint].[GetFullBackupExpireDate]
@DbName [sysname], @ExpireDate DATETIME OUTPUT, @CheckPointDate DATETIME=NULL, @OutputDiagnostics BIT=0
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ERROR int
	SET @RC = 0

	IF(@OutputDiagnostics = 1)
		BEGIN
			PRINT OBJECT_NAME(@@PROCID)
			PRINT N'	@DbName = N''' + ISNULL(@DbName,N'NULL') + ''''
			PRINT N'	@CheckPointDate = N''' + ISNULL(CAST(@CheckPointDate AS nvarchar),N'NULL') + ''''
		END

	IF(@CheckPointDate IS NULL)
		SET @CheckPointDate = GETDATE()

	DECLARE @WeekDay int
	SET DATEFIRST 1
	SELECT @WeekDay = DATEPART(dw, @CheckPointDate)

	DECLARE @FullBackupSchedule int
	SET @FullBackupSchedule = maint.GetFullBackupSchedule(@DbName)

	DECLARE @FullBackupTime int
	SET @FullBackupTime = maint.GetFullBackupTime(@DbName)

	DECLARE @DayIncrement int
	SET @DayIncrement = 1
	WHILE(@DayIncrement <= 7)
		BEGIN
			SET @WeekDay =
				(CASE
					WHEN (@WeekDay < 7) THEN @WeekDay + 1
					ELSE 1 --reset to start of week
				END)
			--NB: bitmask comparision is 0-based
			IF ((@FullBackupSchedule & POWER(2,(@WeekDay-1))) <> 0)
				BREAK
			SET @DayIncrement = @DayIncrement + 1
		END

	SET @CheckPointDate = DATEADD(day,@DayIncrement,@CheckPointDate)
	SET @ExpireDate = util.ChangeDateTime(@CheckPointDate,@FullBackupTime)

	IF(@OutputDiagnostics = 1)
		PRINT N'	@ExpireDate = N''' + ISNULL(CAST(@ExpireDate AS nvarchar),N'NULL') + ''''

	RETURN(0)
END